<template>
	<view>
		<view>
			<view class="cs-select-x">
				<view class="week" @click="showYearSelect">
					<view class="selectweek">
						<view>{{yearName}}</view>
						<i class="nav_icon iconfont iconxiala"></i>
					</view>
				</view>
				<view class="week" @click="showWeekSelect">
					<view class="selectweek">
						<view>{{weekName}}</view>
						<i class="nav_icon iconfont iconxiala"></i>
					</view>
				</view>
			</view>
			<!-- 年度选择列表 -->
			<!-- <view class="pop_bg" v-if="isYear" @tap="isYear = false" catchtouchmove="false">
				<view class="pop_bg_item" @touchmove.stop.prevent="">
					<view class="item" v-for="(item, index) in yearList" :key="index" @tap.stop="changeYear(index)" :class="[index == yearCurrent ? 'left_item_active' : '']">
						{{item.yearName}}<i v-if="index == yearCurrent" class="iconfont iconduigou"></i>
					</view>
				</view>
			</view> -->
			
			<view class="pop" v-if="isYear" @tap="isYear = false">
				<scroll-view scroll-y="true" :class="yearList.length >=10 ? 'popView':'popShort'">
					<view>
						<view class="popItem" :class="index == yearCurrent? 'popActive':''" v-for="(item, index) in yearList" :key="index"
						 @tap.stop="changeYear(index)">{{item.yearName}}</view>
					</view>
				</scroll-view>
			</view>
			
			<!-- 周选择列表 -->
			<!-- <view class="pop_bg" v-if="isWeek" @tap="isWeek = false" catchtouchmove="false">
				<view class="pop_bg_item" @touchmove.stop.prevent="">
					<view class="item" v-for="(item, index) in weekList" :key="index" @tap.stop="changeWeek(index)" :class="[index == weekCurrent ? 'left_item_active' : '']">
						{{item.weekName}}
						<i v-if="index == weekCurrent" class="iconfont iconduigou"></i>
					</view>
				</view>
			</view> -->
			
			<view class="pop"  v-if="isWeek" @tap="isWeek = false">
				<scroll-view scroll-y="true" :class="weekList.length >=10 ? 'popView':'popShort'">
					<view>
						<view class="popItem" :class="index == weekCurrent? 'popActive':''" v-for="(item, index) in weekList" :key="index"
						 @tap.stop="changeWeek(index)">{{item.weekName}}</view>
					</view>
				</scroll-view>
			</view>
			<!-- 表格内容 -->
			<view class="table">
				<!-- 周一至周日 -->
				<view class="table-tr">
					<view class="table-td">
						<view class="sub-table">
							<view class="sub-table-tr">
								<view class="table-th">
									<view class="date">日期</view>
									<view class="time">时段</view>
								</view>
								<view class="table-th" v-for='(item,index) in periodList' :key='index'>
									<view :class="['th-top', days[index] === now_day ? 'th-active' : '']">{{item.week_name}}</view>
									<view :class="['th-bottom', days[index] === now_day ? 'th-active' : '']">{{days[index]}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 课程列表 -->
				<view class="table-tr" v-for="(item,index) in timeList" :key="index">
					<view class="table-td">
						<view class="sub-table">
							<view class="sub-table-tr">
								<!-- 时段列-->
								<view class="sub-table-td">
									<view>{{item.timeName}}</view>
									<view>{{item.timeStart}}</view>
									<view>-</view>
									<view>{{item.timeEnd}}</view>
								</view>
								
								<!-- 课程列 -->
								<view class="sub-table-td" v-for="(val,key) of item.courseArr" :key="key">
									<block v-if="val[tempDays[key]] == null">
										<view class="td-width" @click="linkCourse(item, key, 0)">-</view>
									</block>
									<block v-else>
										<view class="td-width" @click="linkCourse(item, key, 1, val[tempDays[key]])">{{ val[tempDays[key]] }}</view>
									</block>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import del_prop from '@/components/del-prop/del-prop'
	import right_prpup from '@/components/right-prpup/right-prpup'
	import util from '@/common/util.js'
	export default {
		components: {
			vDelProp: del_prop,
			vRightPrpup: right_prpup
		},
		data() {
			return {
				head: false, // 原生右上角弹窗控制
				navList: [
					{title: '删除课表'},
					{title: "创建课表"},
					{title: "年度列表"}
				],
				
				timeList: [], // 时段
				weekList: [], // 周列表
				now_day: new Date().getMonth()+1 + '.' + new Date().getUTCDate(), // 获取当天时间，用来区分每次选择周数如果刚好对应今天则给他一个激活字体样式
				periodList: [ // 周日期
					{week_name: '周一'},
					{week_name: '周二'},
					{week_name: '周三'},
					{week_name: '周四'},
					{week_name: '周五'},
					{week_name: '周六'},
					{week_name: '周日'},
				],
				
				days: [], // 获取星期一-星期天的日期格式如11.1 11.2 11.3
				tempDays: [], // 临时存储一份星期一到星期天的日期，并且是完整的日期
				
				weekCurrent: 0, // 周数选择索引
				weekName: '周选择',
				isWeek: false, // 周列表弹窗控制
				
				yearName: '年度选择',
				isYear: false, // 年度弹窗控制
				yearList: [], // 年度列表
				yearCurrent: 0, // 年度选择索引
				isinitYear: false, // 用来判断是否再次刷新年度列表请求
				
				
				courseArr: [], // 课程数据
				isProp: false, // 删除弹窗显/隐
				
				course_queary: null, // 缓存的数据
			}
		},
		props:{
			stuid: ''
		},
		onNavigationBarButtonTap() {
			this.head = !this.head;
			this.isWeek = false // 隐藏周期列表防止两层遮罩
			this.isYear = false// 隐藏年度列表防止两层遮罩
		},
		onShow() {
			// 判断是否是从添加课程过来的，如果是则应该还原上一次的状态
			this.course_queary = uni.getStorageSync('course_queary') || null
			if (this.course_queary) {
				this.yearName = this.course_queary.yearName
				this.yearCurrent = this.course_queary.yearCurrent
				this.weekName = this.course_queary.weekNums
				this.weekCurrent = this.course_queary.weekCurrent
			}
			this.getData('/stuYear/selYearByChoose', {
				stuId: this.stuid,
				reqMethod: 2
			}, 'year')
		},
		created(){
			// 获取年度列表
			this.getData('/stuYear/selYearByChoose', {
				stuId: this.stuid,
				reqMethod: 2
			}, 'year')
		},
		methods: {
			/**
			 * 获取数据
			 * @param {String} url		请求地址
			 * @param {Object} obj		请求参数
			 * @param {String} mark		标识符可以区分操作不同的色护具
			 */
			getData(url, obj, mark) {
				this.$capi.apiPost(url, obj).then(res => {
					if (res.data.code == 200) {
						switch(mark) {
							case "year":
								this.yearList = res.data.data
								this.isinitYear = true
								
								// 如果是从添加课程过来的，则还原上一次的数据，否则就重新获取数据
								let yearKey = this.course_queary ? this.course_queary.yearKey : this.yearList[0].yearKey
								this.yearName = this.course_queary ? this.course_queary.yearName : this.yearList[0].yearName
								this.yearCurrent = this.course_queary ? this.course_queary.yearCurrent : 0
								this.getData('/stuWeek/selWeekByChoose', {
									yearKey: yearKey,
									stuId: this.stuid,
									reqMethod: 2
								}, 'week')
							break;
							case "week":
								// 1. 周的数据处理,每次更新后先拿第一个周的数据
								this.weekList = res.data.data
								this.weekId = this.weekList[0].weekId 
								this.weekName = this.weekList[0].weekName 
								this.getWeekDay(this.weekList[0].weekStart)
								
								// 2. 拿到周后开始获取时段
								this.getData('/stuTime/selTimeByChoose',{
									stuId: this.stuid,
									weekId: this.weekId,
									reqMethod: 2
								}, 'time')
								
							break;
							case "time":
								uni.removeStorageSync('course_queary') // 清空遗留的课程缓存，避免下一次请求还是拿这个来作为参数
								this.timeList = [] // 每次选择年度/周时应当清空来的时段，避免累加
								
								// 临时创建7个空课程：为了能够正确的摆放每个课程的位置
								// 1. 一个时段 渲染7个课程表格 2个时段则渲染2行, 以此类推
								// 2. 这个时段数组里面要创建一个数组，里面放7个对象，并且放入7个空的周日期来来作为key，但是value先不用赋值，给一个空字符串即可
								// 3. 那么当请求课程的时候就可以根据原来创建的key日期和课程key日期进行比较，来放入表格正确的位置
								// 4. 时段填充好后，则开始获取课程，如果有课程则会进行相应的位置处理
								let data = res.data.data
								data.forEach((item,index) => {
									data[index].timeStart = item.timeStart.substr(0,5) // 由于时段的时间返回的是00:00:00 因此需要将后面的:00给去掉
									data[index].timeEnd = item.timeEnd.substr(0,5)
									data[index].courseArr = new Array(7).fill('').map((item,index) => {
										return {[this.tempDays[index]]: null}
									}) 
									
								})
								this.timeList = data
								// 开始获取课程
								this.getData('/stuCourse/selCourseByWeekId',{
									stuId: this.stuid,
									weekId: this.weekId,
									reqMethod: 2
								}, 'course')
							break;
							case "course":
								// 课程位置摆放处理
								// 1. 第一层循环先根据时段ID 与 课程返回的 时段ID 进行对比
								// 2. 如果一致，在时段数组里进行第二层循环让 课程日期 与当前这个周日期进行对比
								// 3. 存在的话，则在时段的数组里的课程数组加上这个课程日期，就可以显示对应的位置上
								let tempDays = this.tempDays
								this.courseArr = res.data.data
								this.courseArr.forEach((item,index) => {
									this.timeList.forEach((item2,index2) => {
										// 课程的ID与时段ID确保相等
										if (item.stuTime.timeId === item2.timeId) {
											item2.courseArr.forEach((item3,index3) => {
												// 如果课程日期和当前周日期相等，就放到对应的位置,并附上需要的值
												if (item.courseDay === tempDays[index3]) {
													item2.courseArr[index3][this.tempDays[index3]] = item.courseName // 课程名称
													item2.courseRemark = item.courseRemark // 课程备注
													item2.activityType = item.activityType // 课程类型
													item2.courseId = item.courseId // 课程ID
												}
											})
										}
									})
								})
							break;
						}
					} else { // PS： 如果有空数组的400则表示没有数据，如果没有则是参数错误
						 switch(mark) {
							 case 'time':
								this.timeList = [] // 每次选择应当清空来的时段，避免累加
							 break;
							 case 'year': // 如果没有年度，将之前的数组存储的数据全部清空
								this.timeList = []
								this.yearList = []
								this.weekList = []
								this.days = []
								this.weekName = '周选择'
								this.yearName = '年度选择'
								this.yearCurrent = 0
								this.weekCurrent = 0
							 break;
						 }
					}
				})
			},
			
			// 年度列表显示/隐藏
			showYearSelect() {
				this.isYear = !this.isYear
				this.isWeek = false
			},
			
			// 选择年度
			changeYear(index) {
				this.yearName = this.yearList[index].yearName
				this.isYear = false
				let yearKey = this.yearList[this.yearCurrent].yearKey
				if (this.isGetRequest(this.yearCurrent, index)) return // 确保重复选择同一个内容时不能继续请求
				this.yearCurrent = index
				this.getData('/stuWeek/selWeekByChoose', {
					yearKey: yearKey, // 年度Key
					stuId: this.stuid,
					reqMethod: 2
				}, 'week')
			},
			
			// 周期列表展示/隐藏
			showWeekSelect() {
				this.isWeek = !this.isWeek
				this.isYear = false 
			},
			
			// 选择周期列表
			changeWeek(index) {
				this.weekName = this.weekList[index].weekName
				this.isWeek = false
				this.getWeekDay(this.weekList[index].weekStart) // 重新获取对应的周天数
				if (this.isGetRequest(this.weekCurrent, index)) return // 确保重复选择同一个内容时不能继续请求
				this.weekCurrent = index
				// 选择第几周后，重新请求时段
				this.getData('/stuTime/selTimeByChoose',{
					stuId: this.stuid,
					weekId: this.weekList[index].weekId,
					reqMethod: 2
				}, 'time')
			},
			
			// 获取当前周从星期一到星期天的日期
			getWeekDay(currentTime) {
			    var currentDate = new Date(currentTime.replace(/\-/g, '/'))
			    var timesStamp = currentDate.getTime();
			    var currenDay = currentDate.getDay();
			    var dates = [];
			    for (var i = 0; i < 7; i++) {
			        dates.push(util.getLeftTime(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7)))
			    }
				this.days = [] // 每次清空上一次的时间，避免累加
				this.tempDays = []
				this.days = dates.map((item, index) => {
					// 这里要将日期个数带上0
					let year = new Date(item).getFullYear()
					let month = ('0' + item.split('-')[1]).slice(-2)
					let day = ('0' + item.split('-')[2]).slice(-2)
					dates[index] = `${year}-${month}-${day}`
					// 这里要返回给days用来渲染周日期
					return item.substr(5).replace(/\-/g, '.')
				})
				this.tempDays = dates // 每次都要临时存储一份当前星期一到星期天的日期
			},
			
			// 右上角列表选择
			changeNav(item) {
				let title = item.title
				if (title === '删除课表') {
					this.isProp = true // 显示删除课表弹窗
					this.head = false // 隐藏遮罩
				} else if (title === '创建课表') {
					uni.navigateTo({
						url: 'addschedule'
					})
				} else if (title === '年度列表') {
					uni.navigateTo({
						url: './period-list'
					})
				}
				this.head = false // 隐藏右上角菜单弹窗
			},
	
			// 删除课表确定/取消 事件
			changeProp(confirm) {
				if (confirm) { // 确定删除
					this.$capi.apiPost('/stuCourse/delCourseByWeekId', {
						weekId: this.weekId,
						reqMethod: 2
					}).then(res => {
						if (res.data.code == 200) {
							this.showToast('删除完成', '1')
							// 更新课表
							this.getData('/stuYear/selYearByChoose', {
								stuId: this.stuid,
								reqMethod: 2
							}, 'year')
						} else {
							this.showToast(res.data.msg)
						}
					})
				}
				this.isProp = false // 隐藏删除弹窗
				this.head = false // 隐藏右上角菜单弹窗
			},
	
			// 添加课程 / 课程详情事件
			// item: 当前对应课程绑定的属性
			// index: 当前课程的索引值
			// stats: 区分当前点击的是添加还是查看详情
			linkCourse(item, index, stats, courseName = null) {
				// 添加/查看课程之前将相关参数放到缓存中, 以及创建回来后回来我的课表还需要从缓存中进行恢复原来的课表状态
				let course_queary = {
					courseDay: this.tempDays[index], // 课程完整日期
					yearName: this.yearName, // 年名称
					yearKey: this.yearList[this.yearCurrent].yearKey, // 年ID
					yearCurrent: this.yearCurrent,
					weekId: this.weekList[this.weekCurrent].weekId, // 周ID
					weekCurrent: this.weekCurrent,
					weekName: this.periodList[index].week_name ,// 周几
					weekNums: this.weekName, // 第几周
					timeId: item.timeId, // 时段ID
					timeName: item.timeName, // 第几节
				}
				if (courseName) {
					course_queary.courseName = courseName // 课程名称
					course_queary.courseRemark = item.courseRemark // 备注
					course_queary.activityType = item.activityType // 类型
					course_queary.courseId = item.courseId
				}
				uni.setStorageSync('course_queary', course_queary)
				let url = stats === 0 ? '../classSchedule/addcourses' : '../classSchedule/scheduledetails'
				uni.navigateTo({
					url
				})
			},
			
			// 吐司封装
			showToast(title, icon = 'none') {
				uni.showToast({
					title,
					icon
				})
			},
			// 判断是否可以继续请求
			isGetRequest(a, b) {
				return a === b
			}
		},
	
	}
</script>

<style lang="scss">
	page {
		background: #FAFAFA;
	}
	.not_data {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.not_data i {
		font-size: 700upx;
		line-height: 0.8;
		color: rgba(229, 229, 229, 1);
	}
	.not_data_text {
		color: #C2C2C2;
		font-size: 42upx;
		line-height: 40upx;
		margin-top: 15upx;
	}
	.not_data_btn {
		width: 360upx;
		border-radius: 8upx;
		background: #FF9900;
		color: #FFFFFF;
		font-size: 34upx;
		text-align: center;
		line-height: 80upx;
		margin-top: 54upx;
	}

	/* 下拉框 */
	.week {
		width: 100%;
		height: 100upx;
		line-height: 100upx;
		display: flex;
		align-items: center;
		flex-direction: column;
		background: #FFFFFF;

		.selectweek {
			width: 100%;
			display: flex;
			flex-direction: row;
			justify-content: center;
			margin-top: 15upx;
			view {
				font-size: 34upx;
				color: #333333;
				font-weight: 500;
			}
			i {
				margin-left: 18upx;
			}
		}
	}

	// .pop_bg {
	// 	position: fixed;
	// 	left: 0;right: 0;bottom:0;
	// 	z-index: 1;
	// 	background-color: rgba(0, 0, 0, .5);
	// 	.item {
	// 		font-size: 30upx;
	// 		height: 100upx;
	// 		border-top: 1upx solid rgba(229, 229, 229, 1);
	// 		background: #FFFFFF;
	// 		padding-left: 42upx;
	// 		padding-right: 40upx;
	// 		color: #666666;
	// 		display: flex;
	// 		justify-content: space-between;
	// 		align-items: center;
	// 	}

	// 	.left_item_active {
	// 		color: #00D5A2;
	// 	}
	// }
	/* #ifdef APP-PLUS || MP-WEIXIN */
	.pop_bg {
		top: 100upx;
	}
	/* #endif */
	/* #ifdef H5 */
	.pop_bg {
		top: 184upx;
	}
	/* #endif */

	/* 表格 */
	.table {
		display: table;
		width: 100%;
		border-bottom: 1upx solid rgba(229, 229, 229, 1);
		background: #FFFFFF;

		.date {
			display: flex;
			justify-content: flex-end;
			font-size: 18upx;
			color: #333333;
			margin-bottom: 15upx;
		}

		.time {
			display: flex;
			justify-content: flex-start;
			font-size: 18upx;
			color: #333333;
			margin-left: 10upx;
		}

		.table-tr {
			display: table-row;
		}

		.table-td {
			display: table-cell;
		}

		.sub-table {
			width: 100%;
			display: table;
		}

		.sub-table-tr {
			display: table-row;

			.sub-table-td {
				width: 10.9%;
				display: table-cell;
				vertical-align: middle;
				height: 110upx;
				border-right: 1upx solid rgba(229, 229, 229, 1);
				border-top: 1upx solid rgba(229, 229, 229, 1);

				view {
					font-size: 20upx;
					color: #333333;
					line-height: 25upx;
					text-align: center;
				}

				i {
					color: #FF7171;
					position: relative;
					top: 10upx;
					left: 29upx;
					font-size: 60upx;
					line-height: 0;
				}

				.subject {
					color: #333333;
					font-size: 23upx;
					margin-top: 30upx;
				}

				&+.sub-table-td {
					width: 12.7%;
				}
			}

			.table-th {
				width: 10.9%;
				display: table-cell;
				vertical-align: middle;
				height: 100upx;

				&+.table-th {
					width: 12.7%;
					border-left: none;
				}

				.th-top {
					text-align: center;
					font-size: 28upx;
					color: #333333;
				}

				.th-bottom {
					font-size: 20upx;
					text-align: center;
					color: #666666;
				}
			}
		}
	}
	
	// 激活样式
	.th-active{
		color: #ff9900 !important;
	}
	
	// 单个属性
	.td-width{
		margin: auto;
		width: 64upx;
	}
	.dib{
		display: inline-block;
		width: 64upx;
	}
	
	// 下拉选择容器
	.cs-select-x{
		display:flex;
	}
	
	/* pop */
	.pop {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0%;
		left: 0%;
		background: rgba(0, 0, 0, 0.6);
		z-index: 9;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	
	.popView {
		width: 80%;
		height: 70%;
		border-radius: 50upx;
		background: #FFFFFF;
	}
	
	.popShort {
		width: 80%;
		border-radius: 50upx;
		background: #FFFFFF;
	}
	
	.popItem {
		height: 88upx;
		line-height: 88upx;
		text-align: center;
		color: #666666;
		font-size: 36upx;
		border-top: 2upx solid #E5E5E5;
	}
	
	.popItem:first-child {
		border-top: none;
	}
	
	.popActive {
		color: #FF9900;
	}
</style>
